<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Descriptions,
  DescriptionsItem,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
  TimePicker,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

// 预约状态枚举
enum AppointmentStatus {
  CANCELLED = 'cancelled',
  COMPLETED = 'completed',
  CONFIRMED = 'confirmed',
  PENDING = 'pending',
}

// 预约状态配置
const appointmentStatuses = [
  { value: AppointmentStatus.PENDING, label: '待确认' },
  { value: AppointmentStatus.CONFIRMED, label: '已确认' },
  { value: AppointmentStatus.COMPLETED, label: '已完成' },
  { value: AppointmentStatus.CANCELLED, label: '已取消' },
];

// 响应式数据
const loading = ref(false);
const showAddModal = ref(false);
const showDetailModal = ref(false);
const isEdit = ref(false);
const selectedAppointment = ref<any>(null);
const appointmentFormRef = ref();

// 搜索表单
const searchForm = reactive({
  customerName: '',
  phone: '',
  status: undefined,
  appointmentDate: null,
});

// 预约表单
const appointmentForm = reactive({
  id: '',
  customerName: '',
  phone: '',
  appointmentDate: null,
  appointmentTime: null,
  intendedRooms: [],
  status: AppointmentStatus.PENDING,
  requirements: '',
  remarks: '',
});

// 表单验证规则
const appointmentRules = {
  customerName: [{ required: true, message: '请输入客户姓名' }],
  phone: [{ required: true, message: '请输入联系电话' }],
  appointmentDate: [{ required: true, message: '请选择预约日期' }],
  appointmentTime: [{ required: true, message: '请选择预约时间' }],
  intendedRooms: [{ required: true, message: '请选择意向房间' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 模拟数据
const appointments = ref([
  {
    id: '1',
    customerName: '张三',
    phone: '13800138001',
    appointmentDate: dayjs('2024-01-15'),
    appointmentTime: dayjs('2024-01-15 14:00'),
    intendedRooms: ['101', '102'],
    status: AppointmentStatus.PENDING,
    requirements: '需要两室一厅，预算3000-4000元',
    remarks: '客户比较急，希望尽快安排',
    createdAt: dayjs('2024-01-10 10:00'),
    updatedAt: dayjs('2024-01-10 10:00'),
  },
  {
    id: '2',
    customerName: '李四',
    phone: '13800138002',
    appointmentDate: dayjs('2024-01-16'),
    appointmentTime: dayjs('2024-01-16 15:30'),
    intendedRooms: ['201'],
    status: AppointmentStatus.CONFIRMED,
    requirements: '需要一室一厅，靠近地铁站',
    remarks: '已电话确认',
    createdAt: dayjs('2024-01-11 14:30'),
    updatedAt: dayjs('2024-01-12 09:15'),
  },
  {
    id: '3',
    customerName: '王五',
    phone: '13800138003',
    appointmentDate: dayjs('2024-01-14'),
    appointmentTime: dayjs('2024-01-14 16:00'),
    intendedRooms: ['301', '302', '303'],
    status: AppointmentStatus.COMPLETED,
    requirements: '需要三室两厅，精装修',
    remarks: '看房完成，客户满意',
    createdAt: dayjs('2024-01-09 16:20'),
    updatedAt: dayjs('2024-01-14 18:30'),
  },
]);

// 可用房间数据
const availableRooms = ref([
  { id: '101', roomNumber: '101', type: '一室一厅' },
  { id: '102', roomNumber: '102', type: '一室一厅' },
  { id: '201', roomNumber: '201', type: '两室一厅' },
  { id: '202', roomNumber: '202', type: '两室一厅' },
  { id: '301', roomNumber: '301', type: '三室两厅' },
  { id: '302', roomNumber: '302', type: '三室两厅' },
  { id: '303', roomNumber: '303', type: '三室两厅' },
]);

// 统计信息
const statistics = computed(() => {
  const today = dayjs().format('YYYY-MM-DD');
  const todayCount = appointments.value.filter(
    (item) => dayjs(item.appointmentDate).format('YYYY-MM-DD') === today,
  ).length;
  const pendingCount = appointments.value.filter(
    (item) => item.status === AppointmentStatus.PENDING,
  ).length;
  const confirmedCount = appointments.value.filter(
    (item) => item.status === AppointmentStatus.CONFIRMED,
  ).length;
  const completedCount = appointments.value.filter(
    (item) => item.status === AppointmentStatus.COMPLETED,
  ).length;

  return {
    todayCount,
    pendingCount,
    confirmedCount,
    completedCount,
  };
});

// 过滤后的预约列表
const filteredAppointments = computed(() => {
  let filtered = appointments.value;

  if (searchForm.customerName) {
    filtered = filtered.filter((item) =>
      item.customerName.includes(searchForm.customerName),
    );
  }

  if (searchForm.phone) {
    filtered = filtered.filter((item) => item.phone.includes(searchForm.phone));
  }

  if (searchForm.status) {
    filtered = filtered.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.appointmentDate) {
    filtered = filtered.filter((item) =>
      dayjs(item.appointmentDate).isSame(searchForm.appointmentDate, 'day'),
    );
  }

  return filtered;
});

// 表格列定义
const columns = [
  {
    title: '客户姓名',
    dataIndex: 'customerName',
    key: 'customerName',
    width: 120,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 130,
  },
  {
    title: '预约日期',
    dataIndex: 'appointmentDate',
    key: 'appointmentDate',
    width: 120,
    customRender: ({ text }: any) => formatDate(text),
  },
  {
    title: '预约时间',
    dataIndex: 'appointmentTime',
    key: 'appointmentTime',
    width: 100,
    customRender: ({ text }: any) => formatTime(text),
  },
  {
    title: '意向房间',
    dataIndex: 'intendedRooms',
    key: 'intendedRooms',
    width: 150,
    customRender: ({ text }: any) => getRoomNames(text),
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 160,
    customRender: ({ text }: any) => formatDateTime(text),
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 工具函数
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    [AppointmentStatus.PENDING]: 'orange',
    [AppointmentStatus.CONFIRMED]: 'blue',
    [AppointmentStatus.COMPLETED]: 'green',
    [AppointmentStatus.CANCELLED]: 'red',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const statusItem = appointmentStatuses.find((item) => item.value === status);
  return statusItem?.label || status;
};

const formatDate = (date: any) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : '';
  datedayjs.format;
};

const formatTime = (time: any) => {
  return time ? dayjs(time).format('HH:mm') : '';
  timedayjs.format;
};

const formatDateTime = (datetime: any) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm') : '';
  datetimedayjs.format;
};

const getRoomNames = (roomIds: string[]) => {
  if (!roomIds || roomIds.length === 0) return '';
  return roomIds
    .map((id) => {
      const room = availableRooms.value.find((r) => r.id === id);
      return room ? `${room.roomNumber}(${room.type})` : id;
    })
    .join(', ');
};

const disabledDate = (current: any) => {
  return current && current < dayjs().startOf('day');
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
};

const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    phone: '',
    status: undefined,
    appointmentDate: null,
  });
  pagination.current = 1;
};

const handleView = (record: any) => {
  selectedAppointment.value = record;
  showDetailModal.value = true;
};

const handleEdit = (record: any) => {
  isEdit.value = true;
  Object.assign(appointmentForm, {
    ...record,
    appointmentDate: dayjs(record.appointmentDate),
    appointmentTime: dayjs(record.appointmentTime),
  });
  showAddModal.value = true;
};

const handleConfirm = (record: any) => {
  Modal.confirm({
    title: '确认预约',
    content: `确定要确认客户 ${record.customerName} 的预约吗？`,
    onOk: () => {
      const index = appointments.value.findIndex(
        (item) => item.id === record.id,
      );
      if (index !== -1) {
        appointments.value[index].status = AppointmentStatus.CONFIRMED;
        appointments.value[index].updatedAt = dayjs();
        message.success('预约确认成功');
      }
    },
  });
};

const handleComplete = (record: any) => {
  Modal.confirm({
    title: '完成预约',
    content: `确定要标记客户 ${record.customerName} 的预约为已完成吗？`,
    onOk: () => {
      const index = appointments.value.findIndex(
        (item) => item.id === record.id,
      );
      if (index !== -1) {
        appointments.value[index].status = AppointmentStatus.COMPLETED;
        appointments.value[index].updatedAt = dayjs();
        message.success('预约完成');
      }
    },
  });
};

const handleDelete = (record: any) => {
  Modal.confirm({
    title: '删除预约',
    content: `确定要删除客户 ${record.customerName} 的预约吗？`,
    onOk: () => {
      const index = appointments.value.findIndex(
        (item) => item.id === record.id,
      );
      if (index !== -1) {
        appointments.value.splice(index, 1);
        message.success('删除成功');
      }
    },
  });
};

const handleSave = async () => {
  try {
    await appointmentFormRef.value.validate();

    if (isEdit.value) {
      // 编辑模式
      const index = appointments.value.findIndex(
        (item) => item.id === appointmentForm.id,
      );
      if (index !== -1) {
        appointments.value[index] = {
          ...appointmentForm,
          updatedAt: dayjs(),
          updatedAt,
        };
        message.success('编辑成功');
      }
    } else {
      // 新增模式
      const newAppointment = {
        ...appointmentForm,
        id: Date.now().toString(),
        createdAt: dayjs(),
        updatedAt: dayjs(),
      };
      appointments.value.unshift(newAppointment);
      message.success('新增成功');
    }

    handleCancel();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  showAddModal.value = false;
  isEdit.value = false;
  appointmentFormRef.value?.resetFields();
  Object.assign(appointmentForm, {
    id: '',
    customerName: '',
    phone: '',
    appointmentDate: null,
    appointmentTime: null,
    intendedRooms: [],
    status: AppointmentStatus.PENDING,
    requirements: '',
    remarks: '',
  });
};

// 初始化
onMounted(() => {
  // 可以在这里加载数据
});
</script>

<template>
  <div class="appointment-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>预约看房管理</h2>
      <Button type="primary" @click="showAddModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        新增预约
      </Button>
    </div>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form :model="searchForm" layout="inline">
        <FormItem label="客户姓名">
          <Input
            v-model:value="searchForm.customerName"
            placeholder="请输入客户姓名"
          />
        </FormItem>
        <FormItem label="联系电话">
          <Input
            v-model:value="searchForm.phone"
            placeholder="请输入联系电话"
          />
        </FormItem>
        <FormItem label="预约状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
          >
            <SelectOption
              v-for="status in appointmentStatuses"
              :key="status.value"
              :value="status.value"
            >
              {{ status.label }}
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem label="预约日期">
          <DatePicker
            v-model:value="searchForm.appointmentDate"
            placeholder="请选择日期"
            style="width: 150px"
          />
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
          <Button @click="handleReset" style="margin-left: 8px">
            <IconifyIcon icon="ant-design:reload-outlined" />
            重置
          </Button>
        </FormItem>
      </Form>
    </Card>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="今日预约"
          :value="statistics.todayCount"
          prefix=""
          color="#1890ff"
          icon="ant-design:calendar-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="待确认"
          :value="statistics.pendingCount"
          prefix=""
          color="#faad14"
          icon="ant-design:clock-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已确认"
          :value="statistics.confirmedCount"
          prefix=""
          color="#52c41a"
          icon="ant-design:check-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已完成"
          :value="statistics.completedCount"
          prefix=""
          color="#722ed1"
          icon="ant-design:check-square-outlined"
        />
      </Col>
    </Row>

    <!-- 预约列表 -->
    <Card class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredAppointments"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="handleView(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="handleEdit(record)">
                编辑
              </Button>
              <Button
                v-if="record.status === 'pending'"
                type="link"
                size="small"
                @click="handleConfirm(record)"
              >
                确认
              </Button>
              <Button
                v-if="record.status === 'confirmed'"
                type="link"
                size="small"
                @click="handleComplete(record)"
              >
                完成
              </Button>
              <Button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 新增/编辑预约模态框 -->
    <Modal
      v-model:open="showAddModal"
      :title="isEdit ? '编辑预约' : '新增预约'"
      width="800px"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <Form
        ref="appointmentFormRef"
        :model="appointmentForm"
        :rules="appointmentRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="客户姓名" name="customerName">
              <Input
                v-model:value="appointmentForm.customerName"
                placeholder="请输入客户姓名"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="联系电话" name="phone">
              <Input
                v-model:value="appointmentForm.phone"
                placeholder="请输入联系电话"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="预约日期" name="appointmentDate">
              <DatePicker
                v-model:value="appointmentForm.appointmentDate"
                placeholder="请选择预约日期"
                style="width: 100%"
                :disabled-date="disabledDate"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="预约时间" name="appointmentTime">
              <TimePicker
                v-model:value="appointmentForm.appointmentTime"
                placeholder="请选择预约时间"
                style="width: 100%"
                format="HH:mm"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="意向房间" name="intendedRooms">
              <Select
                v-model:value="appointmentForm.intendedRooms"
                mode="multiple"
                placeholder="请选择意向房间"
                style="width: 100%"
              >
                <SelectOption
                  v-for="room in availableRooms"
                  :key="room.id"
                  :value="room.id"
                >
                  {{ room.roomNumber }} ({{ room.type }})
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="预约状态" name="status">
              <Select
                v-model:value="appointmentForm.status"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <SelectOption
                  v-for="status in appointmentStatuses"
                  :key="status.value"
                  :value="status.value"
                >
                  {{ status.label }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="客户需求" name="requirements">
          <Textarea
            v-model:value="appointmentForm.requirements"
            placeholder="请输入客户需求描述"
            :rows="3"
          />
        </FormItem>
        <FormItem label="备注" name="remarks">
          <Textarea
            v-model:value="appointmentForm.remarks"
            placeholder="请输入备注信息"
            :rows="2"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 预约详情模态框 -->
    <Modal
      v-model:open="showDetailModal"
      title="预约详情"
      width="600px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="客户姓名">
          {{ selectedAppointment?.customerName }}
        </DescriptionsItem>
        <DescriptionsItem label="联系电话">
          {{ selectedAppointment?.phone }}
        </DescriptionsItem>
        <DescriptionsItem label="预约日期">
          {{ formatDate(selectedAppointment?.appointmentDate) }}
        </DescriptionsItem>
        <DescriptionsItem label="预约时间">
          {{ formatTime(selectedAppointment?.appointmentTime) }}
        </DescriptionsItem>
        <DescriptionsItem label="预约状态">
          <Tag :color="getStatusColor(selectedAppointment?.status)">
            {{ getStatusText(selectedAppointment?.status) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="意向房间">
          {{ getRoomNames(selectedAppointment?.intendedRooms) }}
        </DescriptionsItem>
        <DescriptionsItem label="客户需求" :span="2">
          {{ selectedAppointment?.requirements || '无' }}
        </DescriptionsItem>
        <DescriptionsItem label="备注" :span="2">
          {{ selectedAppointment?.remarks || '无' }}
        </DescriptionsItem>
        <DescriptionsItem label="创建时间">
          {{ formatDateTime(selectedAppointment?.createdAt) }}
        </DescriptionsItem>
        <DescriptionsItem label="更新时间">
          {{ formatDateTime(selectedAppointment?.updatedAt) }}
        </DescriptionsItem>
      </Descriptions>
    </Modal>
  </div>
</template>

<style scoped>
.appointment-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #1f2937;
}

.search-card {
  margin-bottom: 24px;
}

.statistics-row {
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 24px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-modal-body) {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
